using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Initialform_Files;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Initialform_Files
{
    /// <summary>
    /// 初期表单更新命令处理器
    /// </summary>
    public class UpdateInitialformCommandHandler : IRequestHandler<UpdateInitialformCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Initialform> _initialformRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateInitialformCommandHandler> _logger;

        public UpdateInitialformCommandHandler(
            IBaseRepository<Initialform> initialformRepository,
            IMapper mapper,
            ILogger<UpdateInitialformCommandHandler> logger)
        {
            _initialformRepository = initialformRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理初期表单更新命令
        /// </summary>
        /// <param name="request">初期表单更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateInitialformCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("初期表单更新请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"初期表单更新数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询初期表单
                var initialform = await _initialformRepository.GetByIdAsync(request.InitialId);
                
                if (initialform == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.InitialId} 的初期表单");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的初期表单", data = false };
                }

                // 检查是否已被删除
                if (initialform.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.InitialId} 的初期表单已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "初期表单已被删除", data = false };
                }

                // 更新实体（仅修改备注）
                initialform.Note = request.Note;

                // 保存到数据库
                var result = await _initialformRepository.UpdateAsync(initialform);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功更新初期表单，ID: {request.InitialId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "初期表单更新成功", data = true };
                }
                else
                {
                    _logger.LogError($"更新初期表单失败，ID: {request.InitialId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "初期表单更新失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新初期表单时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}